/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"github.com/pkg/errors"
	"github.com/rs/zerolog/log"
	"github.com/spf13/viper"
	"kvmc/app"
	"strings"

	"github.com/spf13/cobra"
)

// setCmd represents the add command
var setCmd = &cobra.Command{
	Use:   "set",
	Short: "设置cluster与node信息",
	Long:  ``,
	Args: func(cmd *cobra.Command, args []string) error {
		if setOpt.Node.IP == "" && setOpt.Center.Addr == "" && setOpt.DefaultCluster == "" {
			return errors.New("需要设置参数")
		}
		if strings.HasPrefix(setOpt.Center.PrivateKey, "~") {
			setOpt.Center.PrivateKey = viper.GetString("HOME") + strings.TrimPrefix(setOpt.Center.PrivateKey, "~")
		}
		return nil
	},
	Run: func(cmd *cobra.Command, args []string) {
		manager, err := app.NewManager(viper.GetString("configPath"))
		if err != nil {
			log.Err(err).Send()
			return
		}
		manager.Set(setOpt)
		err = manager.Save()
		if err != nil {
			log.Err(err).Send()
			return
		}
	},
}

var setOpt = new(app.SetOption)

func init() {
	rootCmd.AddCommand(setCmd)

	setCmd.Flags().StringVarP(&setOpt.DefaultCluster, "default", "d", "", "设置默认集群")

	setCmd.Flags().StringVarP(&setOpt.ClusterName, "cluster", "c", "", "node的集群名称")
	setCmd.Flags().StringVarP(&setOpt.Node.Name, "name", "n", "", "node的名称")
	setCmd.Flags().StringVarP(&setOpt.Node.IP, "ip", "", "", "node的主机IP")
	setCmd.Flags().StringVarP(&setOpt.Node.Hostname, "hostname", "H", "", "node的主机名称")
	setCmd.MarkFlagsRequiredTogether("name", "ip")

	setCmd.Flags().StringVarP(&setOpt.Center.Addr, "center-addr", "", "", "中转主机地址")
	setCmd.Flags().StringVarP(&setOpt.Center.Username, "center-username", "", "", "中转主机用户名称")
	setCmd.Flags().StringVarP(&setOpt.Center.PrivateKey, "center-privateKey", "", "", "中转主机密钥文件路径")
	setCmd.MarkFlagsRequiredTogether("center-addr", "center-username", "center-privateKey")
}
